package thread;

public class SyncDemo1 {
    static boolean success1;//第一个人是否取款成功
    static boolean success2;//第二个人是否取款成功
    public static void main(String[] args) {
        Bank bank = new Bank();
        int sum=1;
        while(true) {
            Thread t1 = new Thread() {
                public void run() {
                    success1 = bank.getMoney(20000);
                }
            };
            Thread t2 = new Thread() {
                public void run() {
                    success2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();

            try {
                //让主线程卡住，目的是等待t1和t2执行完毕
                Thread.sleep(50);
            } catch (InterruptedException e) {
            }

            if (success1 && success2) {
                System.out.println("两个人都取款成功，可刑可拷");
                System.out.println("一共尝试了"+sum+"次");
                break;
            } else {
                bank.saveAccount(20000);//没成功就重新存起来，重新测试
                sum++;
                success1=false;
                success2=false;
            }
        }
    }
}

class Bank{
    private int account = 20000;//账号余额
    public synchronized boolean getMoney(int money){
        //1查余额
        int account = getAccount();
        //2判断取款是否小于余额
        if(account>=money){
            //3计算新余额
            account = account-money;
            Thread.yield();//让当前线程主动放弃本次剩余时间片，用于模拟执行到这里时没时间了发生线程切换
            //4记账
            saveAccount(account);
            //5允许出钞
            return true;
        }
        //拒绝出钞
        return false;
    }

    public void saveAccount(int account){
        this.account = account;
    }

    public int getAccount(){//查看余额
        return account;
    }
}
